import 'dart:async';
import 'dart:convert';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_confirm_cancel_dialog/common_confirm_cancel_dialog.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/constants/call_back.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/net/server_api.dart';
import 'package:e_reception_flutter/singleton/amap_repository/amap_repository.dart';
import 'package:e_reception_flutter/singleton/location_repository/location_repository.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart'
    hide CompanyInfoBean;
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/choose_city/bean/choose_city_list_item_bean.dart';
import 'package:e_reception_flutter/ui/company/choose_city/choose_city_page.dart';
import 'package:e_reception_flutter/ui/company/company_register/bean/company_register_upload_bean.dart';
import 'package:e_reception_flutter/utils/app_overall_distinguish.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_http_utils.dart';
import 'package:e_reception_flutter/utils/vg_hud_utils.dart';
import 'package:e_reception_flutter/utils/vg_location_utils.dart';
import 'package:e_reception_flutter/utils/vg_matisse_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:e_reception_flutter/vg_widgets/vg_text_field_widget/vg_text_field.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:matisse_android_plugin/export_matisse.dart';
import 'package:vg_base/vg_base_callback.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_permission_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_base/vg_widget_lib.dart';

import 'bean/independent_company_basic_info_bean.dart';

class EnterpriseInformationPage extends StatefulWidget {
  final VoidCallback toJumpCallback;
  final int maxZHCharLimit;
  final bool isShowGoIcon;
  final ValueNotifier<CompanyRegisterUploadBean> onChanged;

  ///路由名称
  static const String ROUTER = "EnterpriseInformationPage";

  const EnterpriseInformationPage(
      {Key key,
      this.toJumpCallback,
      this.maxZHCharLimit,
      this.isShowGoIcon = false,
      this.onChanged})
      : super(key: key);

  @override
  _EnterpriseInformationPageState createState() =>
      _EnterpriseInformationPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context) {
    return RouterUtils.routeForFutureResult(
      context,
      EnterpriseInformationPage(),
      routeName: EnterpriseInformationPage.ROUTER,
    );
  }
}

class _EnterpriseInformationPageState extends State<EnterpriseInformationPage> {
  bool isLightUp = false; //确认按钮是否亮起
  String hintText;
  String mAbbreviation;
  String mFullName;
  String mSpecificAddress;
  TextEditingController _editingController;
  TextEditingController _editingFullNameController;
  TextEditingController _editingCityController;
  TextEditingController _editingSpecificAddressController;
  Map<String, ChooseCityListItemBean> _resultLocationMap;
  CompanyRegisterUploadBean _uploadBean;
  CompanyBasicInfoBean _companyInfoBean;
  ValueNotifier<bool> _isShowFocusLineNotifier;
  FocusNode _focusNode;
  StreamSubscription eventStreamSubscription;

  String editStr;



  VgLocation _locationPlugin;

  @override
  void initState() {
    super.initState();
    eventStreamSubscription =
        VgEventBus.global.on<EventOnTapValueButten>().listen((event) {

          if(_editingFullNameController.text != null && _editingFullNameController.text != ""){
            isLightUp = true;
          }
          if(_editingCityController.text != null && _editingCityController.text != ""){
            isLightUp = true;
          }
          if(_editingSpecificAddressController.text != null && _editingSpecificAddressController.text != ""){
            isLightUp = true;
          }
          if(_editingController.text != null && _editingController.text != "" ){
            isLightUp = true;
          }else{
            isLightUp = false;
          }
          setState(() {});
        });

    _isShowFocusLineNotifier = ValueNotifier(false);
    _focusNode = FocusNode();
    _focusNode.addListener(() {
      if (_focusNode?.hasFocus ?? false) {
        _isShowFocusLineNotifier.value = true;
      } else {
        _isShowFocusLineNotifier.value = false;
      }
    });
    _editingController = TextEditingController()
      ..addListener(() => _notifyChange());
    _editingFullNameController = TextEditingController()
      ..addListener(() => _notifyChange());
    _editingCityController = TextEditingController()
      ..addListener(() => _notifyChange());
    _editingSpecificAddressController = TextEditingController()
      ..addListener(() => _notifyChange());

    VgHttpUtils.get(ServerApi.BASE_URL + "app/appCompanyBasicInfo",
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          // "gps":gps??""
        },
        callback: BaseCallback(onSuccess: (dynamic val) {
          //加载框
          VgHudUtils.hide(context);
          if (val == null) {
            return;
          }
          //val获取的是所有的json值
          IndependentCompanyBasicInfoBean successBean =
          IndependentCompanyBasicInfoBean.fromMap(val);
          _companyInfoBean = successBean?.data?.companyBasicInfo;
          _editingController.text =
              successBean?.data?.companyBasicInfo?.companynick ?? "";
          _editingFullNameController.text =
              successBean?.data?.companyBasicInfo?.companyname ?? "";
          // _resultLocationMap = VgLocationUtils.transStringToMap(
          //     successBean?.data?.companyBasicInfo?.city);
          _editingSpecificAddressController.text =
              successBean?.data?.companyBasicInfo?.userAddress ?? "";
          // initCity(successBean?.data?.companyBasicInfo);
          // if (_companyInfoBean?.type == "00") {}
          setState(() {});
        }, onError: (String msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }));

  }

  // void initCity(CompanyBasicInfoBean companyInfo) {
  //
  //   _resultLocationMap = VgLocationUtils.transStringToMap(companyInfo.userCity);
  //   if (_resultLocationMap != null) {
  //     _setLocationEditingValue();
  //     return;
  //   }
  //
  //   _resultLocationMap = VgLocationUtils.transStringToMap(companyInfo.city);
  //   if (_resultLocationMap != null) {
  //     _setLocationEditingValue();
  //     return;
  //   }
  //
  //   initLocation();
  // }

  String _type(){
    if(_companyInfoBean?.type!=null){
      String registrationType = _companyInfoBean?.type;
      if(registrationType=="04" || registrationType=="00"){
        return registrationType = "企业"; //国有企业//民营企业
      }
      else if(registrationType=="02"){//党政机关
        return registrationType = "单位";
      }
      // if(registrationType=="00"){
      //   registrationType = "民营企业";
      // }
      else if(registrationType=="03"){//大中小学
        return registrationType = "学校";
      }
      else if(registrationType=="01"){//培训机构
        return registrationType = "机构";
      }else{
        return registrationType = "企业";
      }
    }else{
      return "机构";
    }
  }

  void initLocation() {
    _locationPlugin = VgLocation();
    _locationPlugin.requestSingleLocation((locationMap) {
      var transResult = VgLocationUtils.transLocationToMap(locationMap);
      if (transResult == null) {
        return;
      }
      _resultLocationMap = transResult;
      _setLocationEditingValue();
      _notifyChange();
    });
  }

  ///通知更新
  _notifyChange() {
    if (widget?.onChanged == null) {
      return;
    }
    if (_uploadBean == null) {
      _uploadBean = CompanyRegisterUploadBean();
    }
    _uploadBean.setValue(
      locaiton: _editingCityController?.text?.trim(),
      locationMap: _resultLocationMap,
      companyNick: _editingController?.text?.trim(),
      name: _editingFullNameController?.text?.trim(),
      address: _editingSpecificAddressController?.text?.trim(),
    );
    widget?.onChanged?.value = _uploadBean;
  }

  @override
  void dispose() {
    _editingController.dispose();
    _editingFullNameController.dispose();
    _editingCityController.dispose();
    _editingSpecificAddressController.dispose();
    eventStreamSubscription.cancel();
    if (_locationPlugin != null) _locationPlugin.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //设置键盘不弹起组件
      resizeToAvoidBottomPadding: true,
      resizeToAvoidBottomInset: true ,
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      //CommonPackUpKeyboardWidget去除焦点事件
      body: CommonPackUpKeyboardWidget(
        child: Column(
          children: <Widget>[
            _toTopBarWidget(),
            if(isShowBlueBox())
              Container(
                height: 30,
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.only(left: 15, top: 7, bottom: 6),
                color: Color(0x7F1890FF).withOpacity(0.2),
                child: Text("完善所有资料后，显示屏推送的智能海报会更具多样性",
                  style: TextStyle(
                    fontSize: 12,
                    color: Color(0xFF1890FF),
                  ),
                ),
              ),
            Expanded(
              child: ListView(
                children: <Widget>[

                  _uploadLOGO(),
                  SizedBox(
                    height: 20,
                  ),
                  Container(
                    padding: const EdgeInsets.only(left: 21,right: 21),
                    child: _EditTextWithTitleWidget(
                      controller: _editingController,
                      title: "${_type()}简称",
                      line: editStr,
                      // maxLength: 8,
                      hintText: editStr == null ? "-" : "请输入",
                      maxZHCharLimit: 8,
                      toJumpCallback: editStr==null ?(){}  : null,
                    ),
                  ),
                  SizedBox(height: 12),
                  Container(
                    constraints: BoxConstraints(
                        maxHeight: 100,
                    ),
                    padding: const EdgeInsets.only(left: 21,right: 21),
                    child: _EditTextWithTitleWidget(
                      controller: _editingFullNameController,
                      title: "${_type()}全称",
                      line: editStr,
                      // maxLength: 30,
                      maxZHCharLimit:30,
                      hintText: editStr == null ? "-" : "选填",

                      toJumpCallback: editStr==null || !AppOverallDistinguish.comefromAiOrWeStudy() ?(){}  : null,
                      // maxZHCharLimit: 8,
                    ),
                  ),
                  SizedBox(height: 12),
                  Container(
                    padding: const EdgeInsets.only(left: 21,right: 21),
                    child: _EditTextWithTitleWidget(
                      controller: _editingCityController,
                      title: "所在区县",
                      hintText: "请选择",
                      line: editStr,
                      isShowGoIcon: editStr==null ? false : true,
                      toJumpCallback: () async {
                        if(editStr==null || !AppOverallDistinguish.comefromAiOrWeStudy()){
                          return "";
                        }

                        HudUtils.showLoading(context,true);
                        LocationRepository.getInstance().init(callback: (success)async{
                          HudUtils.showLoading(context,false);
                          Map<String, ChooseCityListItemBean> result =
                          await ChooseCityPage.navigatorPush(context,
                              subLevel: 3, selected: _resultLocationMap);
                          if (result == null || result.isEmpty) {
                            return null;
                          }
                          _resultLocationMap = result;
                          _setLocationEditingValue();
                        });
                      },
                    ),
                  ),
                  SizedBox(height: 12),
                  Container(
                    constraints: BoxConstraints(
                      maxHeight: 100
                    ),
                    padding: const EdgeInsets.only(left: 21,right: 21),
                    child: _EditTextWithTitleWidget(
                      controller: _editingSpecificAddressController,
                      title: "详细地址",
                      line: editStr,
                      maxLength: 30,
                      hintText: editStr == null || !AppOverallDistinguish.comefromAiOrWeStudy() ? "-" : "请输入",
                      toJumpCallback: editStr==null || !AppOverallDistinguish.comefromAiOrWeStudy() ?(){}  : null,
                      // maxZHCharLimit: 8,
                    ),
                  ),

                  //选择学校或者企业，注释
                  // _chooseEnterpriseSchool(),
                  // _enterpriseEditBox(),
                  // Container(
                  //   height: 1,
                  //   padding: const EdgeInsets.only(left: 21, right: 21),
                  //   child: Divider(
                  //     height: 1.0,
                  //     indent: 0.0,
                  //     color: Color(0xFF303546),
                  //   ),
                  // ),
                  // SizedBox(height: 12),
                  // _fullName(),
                  // Container(
                  //   height: 1,
                  //   padding: const EdgeInsets.only(left: 21, right: 21),
                  //   child: Divider(
                  //     height: 1.0,
                  //     indent: 0.0,
                  //     color: Color(0xFF303546),
                  //   ),
                  // ),
                  // SizedBox(height: 12),
                  // _cityArrive(),
                  // Container(
                  //   height: 1,
                  //   padding: const EdgeInsets.only(left: 21, right: 21),
                  //   child: Divider(
                  //     height: 1.0,
                  //     indent: 0.0,
                  //     color: Color(0xFF303546),
                  //   ),
                  // ),
                  // SizedBox(height: 12),
                  // _specificAddress(),
                  // Container(
                  //   height: 1,
                  //   padding: const EdgeInsets.only(left: 21, right: 21),
                  //   child: Divider(
                  //     height: 1.0,
                  //     indent: 0.0,
                  //     color: Color(0xFF303546),
                  //   ),
                  // ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  // Widget _chooseEnterpriseSchool() {
  //   return Container(
  //     height: 100,
  //     child: Row(
  //       children: <Widget>[
  //         SizedBox(
  //           width: 60,
  //         ),
  //         GestureDetector(
  //           onTap: () {
  //             if (_companyInfoBean?.type == "00") {
  //               return;
  //             }
  //             _companyInfoBean?.type = "00";
  //             isLightUp = true;
  //             setState(() {});
  //           },
  //           child: Image(
  //             image: _companyInfoBean?.type == "00" ?? false
  //                 ? AssetImage("images/common_selected_ico.png")
  //                 : AssetImage("images/common_unselect_ico.png"),
  //             width: 20,
  //           ),
  //         ),
  //         SizedBox(
  //           width: 8,
  //         ),
  //         Text(
  //           "政府/单位/企业",
  //           style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 14),
  //         ),
  //         SizedBox(
  //           width: 30,
  //         ),
  //         GestureDetector(
  //           onTap: () {
  //             if (_companyInfoBean?.type == "01") {
  //               return;
  //             }
  //             _companyInfoBean?.type = "01";
  //             isLightUp = true;
  //             setState(() {});
  //           },
  //           child: Image(
  //             image: _companyInfoBean?.type == "01" ?? false
  //                 ? AssetImage("images/common_selected_ico.png")
  //                 : AssetImage("images/common_unselect_ico.png"),
  //             width: 20,
  //           ),
  //         ),
  //         SizedBox(
  //           width: 8,
  //         ),
  //         Text(
  //           "学校/培训机构",
  //           style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 14),
  //         ),
  //       ],
  //     ),
  //   );
  // }

  void maxLength(String value) {
    if(value==null || value == ""){return;}
    int maxLength = 60;
    //输入字符串判断是否是字符或汉字
    //如果是汉字-2，字符-1

    for (int i = 0; i < value.length; i++) {
      if (value.codeUnitAt(i) > 122) {
        if(maxLength>=0){
          maxLength = maxLength-2;
        }
      }else{
        if(maxLength>=0){
          maxLength = maxLength-1;
        }
      }
    }
  }

  /// 字符要求：8个汉字或16个英文 //30个汉字或60个英文
  int _changeMaxLimit(String value) {

    int maxLength = 8;
    for (int i = 0; i < value.length; i++) {
      if (value.codeUnitAt(i) > 122) {
        maxLength--;
      }
    }
    return maxLength;
  }

  Future<bool> _withdrawFront() async {
    if(isLightUp == true){
      if(editStr == null){
        RouterUtils.pop(context);
        return false;
      }
      bool result = await CommonConfirmCancelDialog.navigatorPushDialog(context,
          title: "提示",
          content: "退出编辑后将不会保存内容，确认退出？",
          cancelText: "取消",
          confirmText: "确定",
          confirmBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF());
      if(result ?? false) {
        VgToolUtils.removeAllFocus(context);
        RouterUtils.pop(context);
      }
    }else{
      RouterUtils.pop(context);
    }
    return false;
  }


  Widget _toTopBarWidget() {
    return WillPopScope(
      onWillPop: !isLightUp ? null : _withdrawFront,
      child: VgTopBarWidget(
        title: "基本资料",
        rightWidget: _buttonWidget(),
        navFunction:_withdrawFront,
      ),
    );
  }

  Widget _buttonWidget() {
    return Container(
        child: CommonFixedHeightConfirmButtonWidget(
          isAlive: editStr == null ? true :isLightUp,
          width: 48,
          height: 24,
          unSelectBgColor:
              ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
          selectedBgColor:  editStr==null ? Colors.transparent :ThemeRepository.getInstance().getPrimaryColor_1890FF(),
          unSelectTextStyle: TextStyle(
              color: VgColors.INPUT_BG_COLOR,
              fontSize: 12,
              fontWeight: FontWeight.w600),
          selectedTextStyle: TextStyle(
              color: editStr==null?ThemeRepository.getInstance().getPrimaryColor_1890FF() : Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
          text: editStr ?? "修改",
          onTap: () {
            if(editStr == null){
              editStr = "保存";
              setState(() {

              });
              return;
            }
            //提交按钮
            if (isLightUp) {
              _httpSave();
            }
          },
        ),
      );
    //  },
    // );
  }

  void _httpSave()async {
    print("图片路径：${_companyInfoBean.companylogo}");
    if(_companyInfoBean?.companylogo!=null && _companyInfoBean?.companylogo!=""){
      try{
        VgHudUtils.show(context);
        String netUrl=await VgMatisseUploadUtils.uploadSingleImageForFuture(_companyInfoBean?.companylogo);
        _companyInfoBean?.companylogo = netUrl;
      }catch(e){
        return VgToastUtils.toast(context, "请检查网络");
      }
    }
    VgHttpUtils.post(ServerApi.BASE_URL + "app/appEditCompany",
        params: {
          "authId": UserRepository.getInstance().authId ?? "",
          "companyid": _companyInfoBean?.companyid,
          "city": VgLocationUtils.encodeLocationByMap(_resultLocationMap) ?? "",
          "companyname": _editingFullNameController.text,
          "companynick": _editingController.text,
          "companylogo": _companyInfoBean?.companylogo ?? "",
          // "type": _companyInfoBean?.type ?? "",
          "address": _editingSpecificAddressController.text,
        },
        callback: BaseCallback(onSuccess: (dynamic val) {
          VgToastUtils.toast(context, "保存成功");
          _autoLogin(context);
          VgHudUtils.hide(context);
        }, onError: (String msg) {
          VgHudUtils.hide(context);
          VgToastUtils.toast(context, msg);
        }));
  }

  ///切换成功，进行自动登录
  void _autoLogin(BuildContext context) {
    UserRepository.getInstance()
        .loginService(
            isBackIndexPage: false,
            callback: VgBaseCallback(onSuccess: (UserDataBean userDataBean) {
              VgHudUtils.hide(context);
              RouterUtils.pop(context, result: true);
              // VgToastUtils.toast(AppMain.context, "公司切换成功");
            }, onError: (String msg) {
              VgHudUtils.hide(context);
              VgToastUtils.toast(context, msg);
            }))
        .autoLogin();
  }

  Widget _uploadLOGO() {
    return GestureDetector(
      onTap: () async {
        if(editStr == null|| !AppOverallDistinguish.comefromAiOrWeStudy() ){
          return;
        }
        String logo =
            await MatisseUtil.clipOneImage(context, scaleX: 1, scaleY: 1,maxAutoFinish: true,
                onRequestPermission: (msg)async{
              bool result =
              await CommonConfirmCancelDialog.navigatorPushDialog(context,
                title: "提示",
                content: msg,
                cancelText: "取消",
                confirmText: "去授权",
              );
              if (result ?? false) {
                PermissionUtil.openAppSettings();
              }
            });
        if (StringUtils.isEmpty(logo)) {
          return;
        }
        _companyInfoBean.companylogo = logo;
        if (logo != null || logo != "") {
          isLightUp = true;
        }
        setState(() {});
      },
      child: Column(
        children: <Widget>[
          ClipRRect(
            borderRadius: BorderRadius.circular(5),
            child: Container(
              height: 102,
              width: 102,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: ThemeRepository.getInstance().getBgOrSplitColor_191E31()),
              // color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
              child: editStr == null && StringUtils.isEmpty(_companyInfoBean?.companylogo ?? "")  ? Image.asset("images/company_detail_card_info_logo_ico.png") : _toLogP(),
            ),
          ),
        ],
      ),
    );
  }

  Widget _toLogP(){
    return StringUtils.isNotEmpty(_companyInfoBean?.companylogo ?? "")
        ? VgCacheNetWorkImage(
      _companyInfoBean?.companylogo ?? "", width: 102, height: 102,
    )
        : Column(
      children: <Widget>[
        Padding(
          padding: const EdgeInsets.only(
              top: 20.5, bottom: 10.5, left: 34, right: 34),
          child: Image.asset(
            "images/add_ico.png",
            width: 37,
          ),
        ),
        Expanded(
          child: Text(
            "上传LOGO",
            textAlign: TextAlign.center,
            style: TextStyle(color: Color(0xFF3A3F50), fontSize: 12),
          ),
        ),
      ],
    );
  }

  void _setLocationEditingValue() {
    _editingCityController?.text = _initAddressStr();
  }

  String _initAddressStr() {
    String province = _resultLocationMap[CHOOSE_PROVINCE_KEY]?.sname;
    String city = _resultLocationMap[CHOOSE_CITY_KEY]?.sname;
    String district = _resultLocationMap[CHOOSE_DISTRICT_KEY]?.sname;
    if(StringUtils.isEmpty(district)){
      district = "";
    }
    if (province == city) {
      if ("$province$district" != _cityStr() &&
          isNotEmptyText("$province$district")) {
        isLightUp = true;
        setState(() {});
      }
      return "$province$district";
    } else {
      if ("$province$city$district" != _cityStr() &&
          isNotEmptyText("$province$city$district")) {
        isLightUp = true;
        setState(() {});
      }
      return "$province$city$district";
    }
  }

   // ignore: missing_return
   bool isShowBlueBox(){
      if(editStr ==null)return false;
      if (_companyInfoBean == null) return false;
      return StringUtils.isEmpty(_companyInfoBean?.companylogo) ||
       StringUtils.isEmpty(_companyInfoBean?.companynick) ||
       StringUtils.isEmpty(_companyInfoBean?.companyname) ||
       StringUtils.isEmpty(_companyInfoBean?.city) ||
       StringUtils.isEmpty(_companyInfoBean?.userAddress);

   }
  static bool isNotEmptyText(String text){
    return text != null && text.isNotEmpty && text != "";
  }

  String _cityStr(){
    Map<String,dynamic> map = Map<String,dynamic>();
    if(_companyInfoBean?.userCity!=null && _companyInfoBean?.userCity != ""){
      map = json.decode(_companyInfoBean?.userCity);
    }else{
      map = json.decode(_companyInfoBean?.city);
    }

    String  province = map["province"];
    String city = map["province"];
    String district = map["district"];
    if (province == city) {
      return "$province$district";
    } else {
      return "$province$city$district";
    }
  }
}

class _EditTextWithTitleWidget extends StatefulWidget {
  final String title;

  final String line;

  final String hintText;

  final bool isShowGoIcon;

  final VoidCallback toJumpCallback;

  final TextEditingController controller;

  final int maxZHCharLimit;

  final int maxLength;

  const _EditTextWithTitleWidget(
      {Key key,
        this.title,
        this.hintText,
        this.isShowGoIcon = false,
        this.toJumpCallback,
        this.controller, this.maxZHCharLimit, this.line, this.maxLength})
      : super(key: key);

  @override
  _EditTextWithTitleWidgetState createState() =>
      _EditTextWithTitleWidgetState();
}

class _EditTextWithTitleWidgetState extends State<_EditTextWithTitleWidget> {
  FocusNode _focusNode;

  ValueNotifier<bool> _isShowFocusLineNotifier;

  String mAbbreviation;


  @override
  void initState() {
    super.initState();
    _isShowFocusLineNotifier = ValueNotifier(false);
    _focusNode = FocusNode();
    _focusNode.addListener(() {
      if (_focusNode?.hasFocus ?? false) {
        _isShowFocusLineNotifier.value = true;
      } else {
        _isShowFocusLineNotifier.value = false;
      }
    });
  }

  @override
  void dispose() {
    _focusNode?.dispose();
    _isShowFocusLineNotifier?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Container(
          // height: 45,
          child: Row(
            children: <Widget>[
              Container(
                width: 80,
                alignment: Alignment.centerLeft,
                child: Text(
                  widget.title ?? "",
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(
                    color: ThemeRepository.getInstance()
                        .getTextMinorGreyColor_808388(),
                    fontSize: 14,
                  ),
                ),
              ),
              Expanded(
                child: VgTextField(
                  textAlign: TextAlign.start,
                  controller: widget?.controller,
                  maxLines: 3,
                  minLines: 1,
                  maxLength: widget?.maxLength,
                  // overflow: TextOverflow.ellipsis,
                  keyboardType: TextInputType.multiline,
                  focusNode: _focusNode,
                  readOnly: widget.toJumpCallback != null ? true : false,
                  onTap: () {
                    if (widget.toJumpCallback != null) {
                      widget.toJumpCallback();
                    }
                  },
                  onChanged: (String information) {
                     if(widget?.controller?.text == information){
                       VgEventBus.global.send(EventOnTapValueButten(information));
                     }else{
                      VgEventBus.global.send(EventOnTapValueButten(information));
                    }
                    setState(() {});
                  },
                  onSubmitted: (String information) {
                    if(widget?.controller?.text == information) {
                      VgEventBus.global.send(EventOnTapValueButten(information));
                    } else{
                      VgEventBus.global.send(EventOnTapValueButten(information));
                    }
                    setState(() {});
                  },
                  maxLimitLength: widget?.maxZHCharLimit,
                  decoration: InputDecoration(
                    border: InputBorder.none,
                    counterText: "",
                    contentPadding: const EdgeInsets.only(top: 13,bottom: 13),
                    hintText: widget.hintText ?? "",
                    hintStyle: TextStyle(
                        color: widget.hintText=="-"?
                        ThemeRepository.getInstance().getTextMainColor_D0E0F7() :
                        ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
                        fontSize: 14),
                  ),
                  style: TextStyle(
                      fontSize: 14,
                      color: widget.line == null || AppOverallDistinguish.comefromAiOrWeStudy()
                          ? ThemeRepository.getInstance().getTextMainColor_D0E0F7()
                          : Color(0xFFBFC2CC)
                  ),
                ),
              ),
              Opacity(
                opacity: widget.isShowGoIcon && AppOverallDistinguish.comefromAiOrWeStudy() ? 1 : 0,
                child: Container(
                    padding: const EdgeInsets.only(left: 5),
                    child: Image.asset(
                      "images/go_ico.png",
                      width: 6,
                    )),
              )
            ],
          ),
        ),
        Opacity(
          opacity: widget.line!=null && AppOverallDistinguish.comefromAiOrWeStudy() ? 1 : 0,
          child: ValueListenableBuilder(
            builder: (_, value, Widget child) {
              return AnimatedContainer(
                height: 1,
                duration: DEFAULT_ANIM_DURATION,
                color: value
                    ? ThemeRepository.getInstance().getPrimaryColor_1890FF()
                    : Color(0xFF303546),
              );
            },
            valueListenable: _isShowFocusLineNotifier,
          ),
        )
      ],
    );
  }
}


class EventOnTapValueButten{
  final String controllerText;

  EventOnTapValueButten(this.controllerText);

}